#include "RingBuffer.h"

#define ACTUAL_BUFFER_SIZE BUFFER_SIZE+1    // Need one extra for over run

unsigned char buffer[ACTUAL_BUFFER_SIZE];
// If head and tail match then buffer is empty.
// If head is tail - 1 then buffer is full.
int head = 0;   // Always points to empty buffer.
int tail = 0;   // Points to last item in buffer.

// True if added, False if over run.
bool AddToBuffer(unsigned char data){
    if (head + 1 == tail) return 0;
    if (head + 1 == ACTUAL_BUFFER_SIZE && tail == 0) return 0;
    buffer[head] = data;
    head++;
    if (head == ACTUAL_BUFFER_SIZE) head = 0;
    buffer[head] = 0;   // Clear data to make it easier to debug
    return true;
}
// Get oldest data in buffer.  Returns 0 if empty
unsigned char GetOldest(){
    unsigned char data;
    if (tail == head) return 0;
    data = buffer[tail];
    buffer[tail] = 0;   // Clear data to make it easier to debug
    tail++;
    if (tail == ACTUAL_BUFFER_SIZE) tail = 0;
    return data;
}
// Returns number of valid items in buffer.
int Available(){
    if (tail == head){
        return ACTUAL_BUFFER_SIZE - 1;
    }
    else if (tail > head){
        return ACTUAL_BUFFER_SIZE - (tail - head);
    } else {
        return ACTUAL_BUFFER_SIZE - (head - tail);
    }
}